<?php

namespace App\Models;

use Illuminate\Support\Collection;

class DiscountGoods extends Model
{
    protected $table = 'yf_discount_goods';
    protected $primaryKey = 'discount_goods_id';
    public $timestamps = false;
    protected $guarded = ['discount_goods_id'];

    public static function getOpenForumDiscount(array $ids, int $size) : Collection
    {
        $columns = [
            'a.discount_goods_id', 'a.discount_id','a.discount_name', 'a.goods_id', 'a.common_id', 'b.goods_image',
            'a.goods_price', 'a.discount_price', 'a.goods_name', 'a.goods_end_time', 'a.goods_start_time', 'a.goods_lower_limit'
        ];

        return self::buildQuery($columns)
            ->when($ids, function ($query) use ($ids) {
                return $query->whereNotIn('a.discount_goods_id', $ids);
            })
            ->limit($size)
            ->get();
    }

    public static function getDiscountGoodsByIds(array $ids) : Collection
    {
        $now = now()->toDateTimeString();
        return self::where('goods_start_time', '<', $now)
            ->where('goods_end_time', '>', $now)
            ->where('discount_goods_state', 1)
            ->whereIn('discount_goods_id', $ids)
            ->get();
    }

    private static function buildQuery(array $columns)
    {
        $now = now()->toDateTimeString();
        return self::from('yf_discount_goods as a')
            ->select($columns)
            ->leftJoin('yf_goods_base as b', 'b.goods_id', '=', 'a.goods_id')
            ->leftJoin('yf_goods_common as c', 'c.common_id', '=', 'b.common_id')
            ->where([
                ['a.goods_start_time', '<', $now],
                ['a.goods_end_time', '>', $now],
                ['a.discount_goods_state', '=', 2],
                ['b.goods_is_shelves', '=', 1],
                ['b.is_del', '=', 1],
                ['c.common_state', '=', 1],
                ['c.common_verify', '=', 1],
                ['c.is_del', '=', 1]
            ])
            ->latest('a.discount_goods_id');
    }
}
